<template>
  <div class="custom-element-wrapper">
    {{ text }}
  </div>
</template>

<script>
import { ACTION } from '../../../utils/trtcCustomMessageMap';
import { mapState } from 'vuex'; 
export default {
  name: 'CustomElement',
  props: {
    message: {
      type: Object,
      required: true
    },
    isMine: {
      type: Boolean
    }
  },
  computed:{
    ...mapState({
      currentUserProfile: state => state.user.currentUserProfile
    }),
    text(){
      return this.translateCustomMessage(this.message.payload);
    }
  },
  methods:{
    translateCustomMessage(payload){
      switch(payload.data) {
        case 'group_create':
          return payload.extension;
        case 'video_call':
          return this.translateVideoCallMessage(payload);
        case 'shake':
          return this.translateShakeMessage(payload);
        default:
          return '[自定义消息]';
      }
    },
    translateVideoCallMessage(payload){
      let videoPayload = {};
      try{
        videoPayload = JSON.parse(payload.extension);
      } catch(e) {
        videoPayload = {};
      }
      switch(videoPayload.action) {
        case ACTION.VIDEO_CALL_ACTION_DIALING:
          return '[请求通话]';
        case ACTION.VIDEO_CALL_ACTION_SPONSOR_CANCEL:
          return '[取消通话]';
        case ACTION.VIDEO_CALL_ACTION_REJECT:
          return '[拒绝通话]';
        case ACTION.VIDEO_CALL_ACTION_SPONSOR_TIMEOUT:
          return '[无应答]';
        case ACTION.VIDEO_CALL_ACTION_ACCEPTED:
          return '[开始通话]';
        case ACTION.VIDEO_CALL_ACTION_HANGUP:
          return `[结束通话，通话时长：${videoPayload.duration}]`;
        case ACTION.VIDEO_CALL_ACTION_LINE_BUSY:
          return '[正在通话中]';
        case ACTION.VIDEO_CALL_ACTION_ERROR:
          return '[设备异常]';
        default:
          return '[自定义消息]';
      }
    },
    translateShakeMessage(payload){
      let shakePayload = {};
      try{
        shakePayload = JSON.parse(payload.extension);
      } catch(e) {
        shakePayload = {};
      }
      let from = '';
      let to = '';
      if(shakePayload.fromUserID === this.currentUserProfile.userID){
        from = '你';
      } else {
        // 优先级：群名片（单聊消息默认为''）> 昵称 > 用户ID
        from = `"${ shakePayload.fromNameCard || shakePayload.fromNick || shakePayload.fromUserID }"`;
      }
      if(shakePayload.toUserID === shakePayload.fromUserID){
          to = '自己';
      } else if(shakePayload.toUserID === this.currentUserProfile.userID){
          to = '你';
      } else {
        // 优先级：群名片（单聊消息默认为''）> 昵称 > 用户ID
        to = `"${ shakePayload.toNameCard || shakePayload.toNick || shakePayload.toUserID }"`;
      }
      return `${ from }拍了拍${ to }`;
    }
  }
}
</script>

<style scoped>
.custom-element-wrapper{
  background:white;
  padding: 4px 15px;
  border-radius: 3px;
  color: #a5b5c1;
  font-size: 12px;
}
</style>